﻿using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Rmac.DataBase.SqlSugar;
using Rmac.Uitls;
using SqlSugar;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

namespace Radius.Admin.Core
{
    public static class SqlSugarSetup
    {
        /// <summary>
        /// Sqlsugar 上下文初始化
        /// </summary>
        /// <param name="services"></param>
        public static void AddSqlSugar(this IServiceCollection services)
        {
            var config = new ConnectionConfig() { 
                ConnectionString= "DataSource=" + Path.Combine( FileSystem.Current.AppDataDirectory, "rmacdata.db"),
            //@"DataSource=./rmacdata.db",
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
                    {
                        if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                            || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
                            column.IsNullable = true;
                    }
                }
            };
            SqlSugarScope sqlSugar = new SqlSugarScope(config);

            sqlSugar.DbMaintenance.CreateDatabase();

            System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(Rmac.DataBase.Entity.MaterialIssue));
            System.Type[] types = asm.GetExportedTypes();

            // 获取所有实体表
            var entityTypes = types.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false));

            if (entityTypes.Any())
            {
                // 初始化库表结构
                foreach (var entityType in entityTypes)
                {
                    sqlSugar.CodeFirst.InitTables(entityType);
                }
            }
            // 获取所有种子配置-初始化数据
            var seedDataTypes = types.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
                && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
            if (!seedDataTypes.Any()) return;
            foreach (var seedType in seedDataTypes)
            {
                var instance = Activator.CreateInstance(seedType);

                var hasDataMethod = seedType.GetMethod("HasData");
                var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
                if (seedData == null) continue;

                var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();

                var seedDataTable = seedData.ToList().ToDataTable();
                seedDataTable.TableName = sqlSugar.EntityMaintenance.GetEntityInfo(entityType).DbTableName;

                string[] whereColumns = { "Code" };
                var storage = sqlSugar.Storageable(seedDataTable).WhereColumns(whereColumns).ToStorage();
                storage.AsInsertable.ExecuteCommand();
            }

            services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
            services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
        }
    }
}
